package ums.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import ums.model.User;
import ums.service.UserManager;
import ums.service.UserService;
import util.SpringUtil;

/**
 * @author liangzhenghui
 * @date Aug 25, 2013    12:40:27 AM
 */
public class LoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = -6232539424699026999L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		JSONObject json = new JSONObject();
		String userid = req.getParameter("userid");
		String password = req.getParameter("password");
		UserManager userManager = UserManager.getInstance();
		Boolean result = userManager.isExists(userid, password);
		if(result) {
			HttpSession session = req.getSession(true);
			UserService userService = (UserService)SpringUtil.getBean("userService");
			User user = userService.getUserByUserid(userid);
			session.setAttribute("user", user);
		}
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();
		json.put("result", result);
		out.print(json.toString());
	}
}
